<template>
  <div class="pet-lost-container">
    <!-- 导航栏 -->
    <NavigationBar />

    <!-- 主内容区 -->
    <main class="main-content">
      <section class="lost-pets-section">
        <h1 class="section-title">走失宠物列表</h1>

        <div v-if="loading" class="loading-spinner">
          <div class="spinner"></div>
          <p>加载中...</p>
        </div>

        <div v-else-if="lostPets.length > 0" class="lost-pets-list">
          <div v-for="pet in lostPets" :key="pet.id" class="lost-pet-card">
            <div class="pet-image-container" v-if="pet.photo">
              <img :src="pet.photo" :alt="pet.name" class="pet-photo" loading="lazy" />
            </div>

            <div class="pet-info">
              <h3 class="pet-name">{{ pet.name }}</h3>
              <p class="pet-description">{{ pet.description }}</p>

              <div class="pet-meta">
                <div class="meta-item">
                  <i class="fas fa-map-marker-alt"></i>
                  <div class="meta-content">
                    <span class="meta-label">走失地点</span>
                    <span class="meta-value">{{ pet.location }}</span>
                  </div>
                </div>
                <div class="meta-item">
                  <i class="fas fa-phone"></i>
                  <div class="meta-content">
                    <span class="meta-label">联系方式</span>
                    <span class="meta-value">{{ pet.contact }}</span>
                  </div>
                </div>
                <div class="meta-item">
                  <i class="fas fa-calendar-alt"></i>
                  <div class="meta-content">
                    <span class="meta-label">走失时间</span>
                    <span class="meta-value">{{ formatDate(pet.date) }}</span>
                  </div>
                </div>
              </div>

              <!-- 只有can_edit为true时才显示"已找到"按钮 -->
              <button v-if="pet.can_edit" class="found-button" @click="confirmRemovePet(pet)">
                <i class="fas fa-check"></i> 已找到
              </button>
            </div>
          </div>
        </div>

        <div v-else class="no-pets-message">
          <div class="empty-state-icon">
            <i class="fas fa-paw"></i>
          </div>
          <p>暂无走失宠物信息</p>
          <button class="report-button" @click="showModal = true">
            <span class="plus-icon">+</span> 挂失宠物
          </button>
        </div>
      </section>
    </main>

    <!-- 浮动加号按钮 -->
    <div v-if="lostPets.length > 0" class="floating-action-button">
      <button class="report-button" @click="showModal = true" title="挂失宠物">
        <span class="plus-icon">+</span>
      </button>
    </div>

    <Footer />

    <!-- 挂失弹窗 -->
    <div v-if="showModal" class="modal-overlay" @click.self="closeModal">
      <div class="modal-content">
        <button class="close-button" @click="closeModal">&times;</button>
        <h2>宠物挂失信息</h2>
        <form @submit.prevent="submitLostPet" class="lost-pet-form">
          <div class="form-group">
            <label for="name">宠物名称 *</label>
            <input type="text" id="name" v-model="lostPet.name" placeholder="请输入宠物名称" required />
          </div>

          <div class="form-group">
            <label for="description">描述 *</label>
            <textarea id="description" v-model="lostPet.description" placeholder="请描述宠物的特征、习性等" required></textarea>
          </div>

          <div class="form-group">
            <label for="contact">联系方式 *</label>
            <input type="text" id="contact" v-model="lostPet.contact" placeholder="请输入您的联系方式" required />
          </div>

          <div class="form-group">
            <label for="location">走失地点 *</label>
            <input type="text" id="location" v-model="lostPet.location" placeholder="请输入宠物走失的地点" required />
          </div>

          <div class="form-group">
            <label for="photo">宠物照片</label>
            <div class="photo-upload-container">
              <label class="upload-area" :class="{ 'has-photo': lostPet.photo }">
                <input type="file" id="photo" @change="handlePhotoUpload" accept="image/*" class="file-input" />
                <template v-if="!lostPet.photo">
                  <i class="fas fa-camera"></i>
                  <span>点击上传照片</span>
                </template>
                <img v-else :src="lostPet.photo" alt="预览" class="photo-preview" />
              </label>
              <button v-if="lostPet.photo" type="button" class="remove-photo-button" @click="lostPet.photo = ''">
                <i class="fas fa-times"></i>
              </button>
            </div>
            <p class="upload-hint">支持 JPG/PNG 格式，大小不超过 2MB</p>
          </div>

          <div class="form-actions">
            <button type="button" class="cancel-button" @click="closeModal">取消</button>
            <button type="submit" class="submit-button" :disabled="submitting">
              <span v-if="!submitting">提交挂失信息</span>
              <span v-else class="submit-loading">
                <i class="fas fa-spinner fa-spin"></i> 提交中...
              </span>
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 确认弹窗 -->
    <div v-if="showConfirmModal" class="modal-overlay" @click.self="showConfirmModal = false">
      <div class="modal-content confirm-modal">
        <h3>确认取消挂失</h3>
        <p>确定要将 {{ petToRemove?.name }} 标记为已找到吗？</p>
        <div class="confirm-buttons">
          <button class="cancel-button" @click="showConfirmModal = false">取消</button>
          <button class="confirm-button" @click="removePet">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import NavigationBar from '@/components/NavigationBar.vue'
import Footer from '@/components/Footer.vue'

const loading = ref(true)
const showModal = ref(false)
const showConfirmModal = ref(false)
const submitting = ref(false)
const petToRemove = ref(null)
const lostPets = ref([])
const lostPet = ref({
  id: Date.now(),
  name: '',
  description: '',
  contact: '',
  location: '',
  date: new Date(),
  photo: ''
})

onMounted(() => {
  loadLostPets()
})

const loadLostPets = async () => {
  try {
    loading.value = true;
    const token = localStorage.getItem('token');

    // Add more detailed error if token is missing
    if (!token) {
      throw new Error('用户未登录，请先登录');
    }

    // Verify token format (optional debugging)
    console.log('Token being sent:', token);

    const response = await fetch('http://localhost:3000/api/lost-pets', {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });

    if (!response.ok) {
      // Try to get more detailed error info
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.error || `请求失败: ${response.statusText}`);
    }

    const data = await response.json();
    lostPets.value = data;
  } catch (error) {
    console.error('加载挂失列表失败:', error);
    // Show more user-friendly error message
    alert(`加载失败: ${error.message}`);

    // Optional: redirect to login if token is invalid
    if (error.message.includes('token') || error.message.includes('令牌')) {
      router.push('/login');
    }
  } finally {
    loading.value = false;
  }
};

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const handlePhotoUpload = (event) => {
  const file = event.target.files[0]
  if (!file) return

  if (!file.type.match('image.*')) {
    alert('请选择图片文件 (JPG/PNG)')
    return
  }

  if (file.size > 2 * 1024 * 1024) {
    alert('图片大小不能超过2MB')
    return
  }

  const reader = new FileReader()
  reader.onload = (e) => {
    lostPet.value.photo = e.target.result
  }
  reader.readAsDataURL(file)
}

const submitLostPet = async () => {
  submitting.value = true;

  try {
    const response = await fetch('http://localhost:3000/api/lost-pets', {  // 确保完整URL
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify({
        ...lostPet.value,
        // 确保数据结构与后端期望的一致
        // 可能需要移除前端生成的id，让数据库自动生成
      })
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.error || '提交失败');
    }

    await loadLostPets();
    closeModal();
    alert('挂失信息提交成功！');
  } catch (error) {
    console.error('提交失败:', error);
    alert(`提交失败: ${error.message}`);
  } finally {
    submitting.value = false;
  }
};

const resetForm = () => {
  lostPet.value = {
    id: Date.now(),
    name: '',
    description: '',
    contact: '',
    location: '',
    date: new Date(),
    photo: ''
  }
}

const closeModal = () => {
  showModal.value = false
  resetForm()
}

const confirmRemovePet = (pet) => {
  if (!pet.can_edit) {
    alert('您无权操作此记录')
    return
  }
  petToRemove.value = pet
  showConfirmModal.value = true
}

const removePet = async () => {
  if (!petToRemove.value?.can_edit) {
    alert('您无权操作此记录')
    return
  }

  try {
    const response = await fetch(`/api/lost-pets/${petToRemove.value.id}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })

    if (!response.ok) throw new Error('操作失败')

    await loadLostPets()
    showConfirmModal.value = false
    alert('已成功标记为已找到！')
  } catch (error) {
    console.error('操作失败:', error)
    alert('操作失败')
  }
}
</script>

<style scoped>
.pet-lost-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.main-content {
  flex: 1;
  padding: 2rem 1rem;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

.section-title {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 2rem;
  font-size: 2rem;
  font-weight: 600;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 3rem 0;
}

.spinner {
  width: 50px;
  height: 50px;
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top-color: #42b983;
  animation: spin 1s ease-in-out infinite;
  margin-bottom: 1rem;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.lost-pets-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 1.5rem;
  margin-top: 1.5rem;
}

.lost-pet-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.lost-pet-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.pet-image-container {
  width: 100%;
  height: 50vh;
  overflow: hidden;
}

.pet-photo {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.lost-pet-card:hover .pet-photo {
  transform: scale(1.05);
}


.pet-info {
  padding: 1.25rem;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.pet-name {
  margin: 0;
  color: #2c3e50;
  font-size: 1.4rem;
  font-weight: 600;
  border-bottom: 2px solid #42b983;
  padding-bottom: 0.5rem;
}

.pet-description {
  color: #555;
  margin: 0;
  line-height: 1.6;
  font-size: 0.95rem;
}

/* 元信息整体样式 */
.pet-meta {
  display: flex;
  flex-direction: column;
  gap: 0.8rem;
  margin-top: 0.5rem;
  background-color: #f8f9fa;
  padding: 1rem;
  border-radius: 8px;
  border-left: 4px solid #42b983;
}

/* 单个元信息项样式 */
.meta-item {
  display: flex;
  align-items: flex-start;
  gap: 0.8rem;
}

.meta-item i {
  color: #42b983;
  font-size: 1.1rem;
  margin-top: 0.2rem;
  min-width: 20px;
  text-align: center;
}

.meta-content {
  display: flex;
  flex-direction: column;
  gap: 0.2rem;
}

.meta-label {
  font-size: 0.8rem;
  color: #6c757d;
  font-weight: 500;
}

.meta-value {
  font-size: 0.95rem;
  color: #343a40;
  font-weight: 500;
  word-break: break-word;
}

/* 已找到按钮样式 */
.found-button {
  margin-top: 1rem;
  padding: 0.7rem 1rem;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  width: 100%;
}

.found-button:hover {
  background-color: #3aa876;
  transform: translateY(-2px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.found-button i {
  font-size: 0.9rem;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .pet-info {
    padding: 1rem;
  }

  .pet-name {
    font-size: 1.3rem;
  }

  .pet-meta {
    padding: 0.8rem;
    gap: 0.7rem;
  }

  .meta-item {
    gap: 0.7rem;
  }
}

.no-pets-message {
  text-align: center;
  padding: 3rem 1rem;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.empty-state-icon {
  font-size: 3rem;
  color: #42b983;
  margin-bottom: 1.5rem;
}

.no-pets-message p {
  color: #666;
  margin-bottom: 1.5rem;
  font-size: 1.1rem;
}

/* 加号按钮样式 */
.plus-icon {
  display: inline-block;
  font-size: 1.5em;
  font-weight: bold;
  line-height: 1;
  vertical-align: middle;
  margin-right: 0.3em;
  transition: transform 0.2s;
}

.report-button {
  padding: 0.75rem 1.5rem;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.2s;
  display: inline-flex;
  align-items: center;
}

.report-button:hover {
  background-color: #3aa876;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.report-button:hover .plus-icon {
  transform: scale(1.2);
}

/* 浮动按钮 */
.floating-action-button {
  position: fixed;
  bottom: 2rem;
  right: 2rem;
  z-index: 100;
}

.floating-action-button .report-button {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(66, 185, 131, 0.3);
  font-size: 1.8rem;
}

.floating-action-button .plus-icon {
  margin-right: 0;
  font-size: 2.2rem;
  line-height: 0.8;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 25px;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  position: relative;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.close-button {
  position: absolute;
  top: 10px;
  right: 10px;
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #888;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s;
}

.close-button:hover {
  background-color: #f5f5f5;
}

/* 表单样式 */
.lost-pet-form {
  padding: 0.5rem;
}

.form-group {
  margin-bottom: 1.25rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #2c3e50;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 1rem;
  transition: border-color 0.2s;
}

.form-group input:focus,
.form-group textarea:focus {
  border-color: #42b983;
  outline: none;
  box-shadow: 0 0 0 2px rgba(66, 185, 131, 0.2);
}

.form-group textarea {
  min-height: 100px;
  resize: vertical;
}

.photo-upload-container {
  position: relative;
  margin-bottom: 0.5rem;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 2px dashed #ddd;
  border-radius: 6px;
  padding: 1.5rem;
  cursor: pointer;
  transition: all 0.2s;
  height: 150px;
}

.upload-area:hover {
  border-color: #42b983;
  background-color: rgba(66, 185, 131, 0.05);
}

.upload-area.has-photo {
  border: none;
  padding: 0;
  height: auto;
}

.upload-area i {
  font-size: 2rem;
  color: #42b983;
  margin-bottom: 0.5rem;
}

.upload-area span {
  color: #666;
}

.file-input {
  display: none;
}

.photo-preview {
  width: 100%;
  max-height: 200px;
  object-fit: contain;
  border-radius: 4px;
}

.remove-photo-button {
  position: absolute;
  top: 0.5rem;
  right: 0.5rem;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  border: none;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.2s;
}

.remove-photo-button:hover {
  background: rgba(0, 0, 0, 0.8);
}

.upload-hint {
  font-size: 0.8rem;
  color: #888;
  margin-top: 0.25rem;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 1.5rem;
}

.cancel-button {
  padding: 0.75rem 1.5rem;
  background-color: #f1f1f1;
  color: #666;
  border: none;
  border-radius: 6px;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.2s;
}

.cancel-button:hover {
  background-color: #e0e0e0;
  transform: translateY(-1px);
}

.submit-button {
  padding: 0.75rem 1.5rem;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.2s;
}

.submit-button:hover:not(:disabled) {
  background-color: #3aa876;
  transform: translateY(-1px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.submit-button:disabled {
  background-color: #a0d9bb;
  cursor: not-allowed;
}

.submit-loading i {
  animation: spin 1s linear infinite;
  margin-right: 0.5rem;
}

/* 确认弹窗样式 */
.confirm-modal {
  text-align: center;
  max-width: 400px;
}

.confirm-buttons {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
}

.confirm-button {
  padding: 0.75rem 1.5rem;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
}

.confirm-button:hover {
  background-color: #3aa876;
  transform: translateY(-1px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .lost-pets-list {
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  }

  .section-title {
    font-size: 1.5rem;
  }

  .floating-action-button {
    bottom: 1.5rem;
    right: 1.5rem;
  }
}

@media (max-width: 480px) {
  .main-content {
    padding: 1rem 0.5rem;
  }

  .lost-pets-list {
    grid-template-columns: 1fr;
  }

  .form-actions {
    flex-direction: column;
  }

  .cancel-button,
  .submit-button {
    width: 100%;
  }
}
</style>